package com.shixj.easy.spider.api.async;

import com.shixj.easy.spider.model.Chapter;
import com.shixj.easy.spider.model.Guest;
import com.shixj.easy.spider.model.Novel;
import com.shixj.easy.spider.service.ReadService;
import com.shixj.easy.spider.service.WeixinAuthcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.vankid.common.model.base.CommonResponse;
import pers.vankid.common.utils.page.PageResponse;
import pers.vankid.common.utils.page.PageUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by shixj on 2018/1/16.
 */
@RestController()
public class ReadController {
    @Autowired
    ReadService readService;
    @Autowired
    WeixinAuthcService weixinAuthcService;

    @PostMapping("novel/list/{num}/{size}")
    CommonResponse<PageResponse<List<Novel>>> read(@PathVariable int num, @PathVariable int size, @RequestBody Novel novel,HttpServletRequest request) {
        Long guestId = Long.valueOf(request.getHeader("id"));
        return CommonResponse.buildGetSuccessResponse(PageUtil.getPageResponse(readService.getNovelList(num, size,novel,guestId)));
    }

    @GetMapping("novel/{novelId}/{sourceId}")
    CommonResponse<Chapter> read(@PathVariable Long novelId, @PathVariable Long sourceId, HttpServletRequest request) {
        try {
            Long guestId = Long.valueOf(request.getHeader("id"));
            return CommonResponse.buildGetSuccessResponse(readService.read(guestId, novelId, sourceId, 0L));
        } catch (Exception e) {
            return CommonResponse.buildExceptionResponse(e);
        }
    }
    @PostMapping("novel")
    CommonResponse<Novel> getNovelById(@RequestBody Chapter chapter) {
        return CommonResponse.buildGetSuccessResponse(readService.getNovelById(chapter));
    }

    @GetMapping("novel/{novelId}/{num}/{size}")
    CommonResponse<PageResponse<List<Chapter>>> read(@PathVariable Long novelId, @PathVariable int num, @PathVariable int size, HttpServletRequest request) {
        Long guestId = Long.valueOf(request.getHeader("id"));
        return CommonResponse.buildGetSuccessResponse(PageUtil.getPageResponse(readService.readList(guestId, novelId, num, size)));
    }

    @PostMapping("login")
    public CommonResponse<Guest> getWeixinUser(@RequestBody Guest guest) {
        try {
            return CommonResponse.buildDefaultSuccessResponse("登陆成功！", weixinAuthcService.login(guest));
        } catch (Exception e) {
            return CommonResponse.buildExceptionResponse(e);
        }
    }
}
